import java.util.LinkedList;
import java.util.Queue;

public class Solution1162 {
    public int maxDistance(int[][] grid) {
        int[] dx=new int[]{0,1,0,-1};
        int[] dy=new int[]{1,0,-1,0};
        Queue<int[]> queue=new LinkedList<>();
        int[][] dis=new int[grid.length][grid[0].length];
        for (int i=0;i<grid.length;i++){
            for (int j=0;j<grid[0].length;j++){
                dis[i][j]=-1;
                if (grid[i][j]==1){
                    queue.offer(new int[]{i,j});
                    dis[i][j]=0;
                }
            }
        }
        int ans=-1;
        while (!queue.isEmpty()){
            int[] t=queue.poll();
            for (int i=0;i<4;i++){
                int x=t[0]+dx[i];
                int y=t[1]+dy[i];
                if (x>=0 && x<grid.length && y>=0 && y<grid[0].length && dis[x][y]==-1){
                    dis[x][y]=dis[t[0]][t[1]]+1;
                    ans=Math.max(ans,dis[x][y]);
                    queue.offer(new int[]{x,y});
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1162().maxDistance(new int[][]{{1,0,1},{0,0,0},{1,0,1}}));
    }
}
